<?php

	class CsvImportFile extends AppModel
	{
		var $name = "CsvImportFile";
		
		var $fieldProperties = array(
			'fields_map' => array("fieldModifier"=>'toggleSerialized'),
			'other_information' => array("fieldModifier"=>'toggleSerialized')
		);
		var $cacheFields = array("fileInfo"=>"onUpdate");
		function getFileInfo($csvFileId)
		{
			$fileInfo = false;//GigaModelCache::read($this->alias,$csvFileId,"fileInfo",array("duration"=>"+10 minutes"));
			if($fileInfo === false || 1==1)
			{
				$fileInfo = $this->findById($csvFileId);
				$fileInfo = $fileInfo[$this->alias];
				//GigaModelCache::write($this->alias,$csvFileId,"fileInfo",$fileInfo,array("duration"=>"+10 minutes"));
			}
			return $fileInfo;
		}
		
		function setFieldMap($csvFileId,$fieldMap)
		{
			$this->id = $csvFileId;
			$this->saveField('fields_map',$fieldMap);	
		}
		
		function isRunning($fileId, $fileInfo)
		{
			$isRunning = true;
			if(!$fileInfo['is_running'])
			{
				$isRunning = false;
			}else if(strtotime('-2 hours') > strtotime($fileInfo['last_ran']))
			{
				$isRunning = false;
			}
			return $isRunning;
		}

		function flagAsRunning($fileId)
		{
			$this->id = $fileId;
			$fileInfo = $this->getFileInfo($fileId);
			if(!$fileInfo['is_active'])
			{
				$this->saveField('is_active',1);
			}
			$this->id = $fileId;
			$this->saveField('is_running',1);
			$this->saveField('last_ran',date("Y-m-d H:i:s"));
		}
		function removeRunningFlag($fileId,$completed,$lastRowNumber)
		{
			$this->id = $fileId;
			$this->saveField('is_running',0);
			if($completed)
			{
				$this->saveField('is_completed',1);
			}
			$this->saveField('last_row_number',$lastRowNumber);
		}
		
		function getPending()
		{
			$now = date("Y-m-d H:i:s");
			$pending = $this->find("all",array('recursive'=>-1,"conditions"=>array("is_active"=>1,'is_completed'=>0,"OR"=>array('is_running'=>0,array('is_running'=>1,'last_ran < DATE_SUB("'.$now.'",INTERVAL 3 HOUR)')))));
			return $pending;
		}
	}
?>